package com.yang.news.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Http请求log记录过滤器
 * @author Billyang
 * @date 2024/9/14 15:08
 */
public class RequestLogFilter extends OncePerRequestFilter {

    private final Logger log = LoggerFactory.getLogger("only_http");//用于打印到http文件的

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // Wrapper 封装 Request 和 Response
        ContentCachingRequestWrapper cachingRequest = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper cachingResponse = new ContentCachingResponseWrapper(response);

        // 继续执行请求链
        filterChain.doFilter(cachingRequest, cachingResponse);

        /**
         * 在请求完成后记录请求、响应日志
         */
        // 请求方法
        String method = request.getMethod();
        // URI
        String uri = request.getRequestURI();
        // 请求体
        byte[] requestContent = cachingRequest.getContentAsByteArray();

        log.info("Request => {} {} {}", method, uri, new String(requestContent));

        // 响应状态
        int status = response.getStatus();
        // 响应体
        byte[] responseContent = cachingResponse.getContentAsByteArray();

        String result = new String(responseContent);
        if(result.length() > 512){
            result = result.substring(0, 512)+"...";
        }
        log.info("Response <= {} {}", status, result);

        /**
         * 把缓存的响应数据，响应给客户端
         */
        cachingResponse.copyBodyToResponse();
    }
}
